package tcsdesign

import (
	"encoding/json"
	"fmt"
	"game/game-design/util"
	"reflect"
	"strconv"
)

type TcsDesignParser struct {
}

func (p *TcsDesignParser) ParseList(value string, eleType reflect.Type) reflect.Value {
	if eleType.Elem().Kind() == reflect.Int32 {
		var i32s []int32
		json.Unmarshal([]byte(value), &i32s)
		return reflect.ValueOf(i32s)

	} else if eleType.Elem().Kind() == reflect.Int64 {
		var i64s []int64
		json.Unmarshal([]byte(value), &i64s)
		return reflect.ValueOf(i64s)

	} else if eleType.Elem().Kind() == reflect.Float32 {
		var f32s []float32
		json.Unmarshal([]byte(value), &f32s)
		return reflect.ValueOf(f32s)

	} else if eleType.Elem().Kind() == reflect.String {
		var strs []string
		json.Unmarshal([]byte(value), &strs)
		return reflect.ValueOf(strs)

	} else if eleType.Elem().Kind() == reflect.Struct {
		var strs []interface{}
		json.Unmarshal([]byte(value), &strs)

		result := reflect.New(eleType).Elem()
		for _, v := range strs {
			jValue, _ := json.Marshal(v)
			rValue := p.ParseStruct(string(jValue), eleType.Elem())
			result = reflect.Append(result, rValue.Elem())
		}
		return result
	} else {
		var empty []interface{}
		return reflect.ValueOf(empty)
	}
}
func (p *TcsDesignParser) ParseStruct(value string, eleType reflect.Type) reflect.Value {
	objValue := reflect.New(eleType)
	if value == "" {
		return objValue
	}
	var data []interface{}
	err := json.Unmarshal([]byte(value), &data)
	if err != nil {
		return objValue
	}
	for i, v := range data {
		objField := objValue.Elem().Field(i)

		stringValue := fmt.Sprintf("%v", v)
		if objField.Kind() == reflect.Int32 {
			i32, err := strconv.ParseInt(stringValue, 10, 32)
			if err == nil {
				util.ReflectSetInt(objField, i32)
			}
		} else if objField.Kind() == reflect.Int64 {
			i64, err := strconv.ParseInt(stringValue, 10, 64)
			if err == nil {
				util.ReflectSetInt(objField, i64)
			}
		} else if objField.Kind() == reflect.String {
			util.ReflectSetString(objField, stringValue)

		} //未处理的类型
	}
	return objValue
}
